<?php

namespace App\Console\Commands;

use App\Http\Controllers\Resource\XytsController;
use App\Models\ResourceBusinessName;
use App\Models\ResourceTypeExternal;
use App\Models\ResourceXyts;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

/**
 *新语听书
 */
class XytsMysqlData extends Command
{

    // 使用 命令行执行  php artisan command:XytsMysqlData

    protected $limit = 100; //每页限制条数
    protected $up_start_page = 1; //开始页，默认为 1
    protected $resource_business_id = 6; //资源商id

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:XytsMysqlData';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步新语听书数据到数据库';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $resourceBusinessNameModel = new  ResourceBusinessName();
        $resource_business_name_info = $resourceBusinessNameModel->where('id', $this->resource_business_id)->where('is_del', 1)->first();
        if (empty($resource_business_name_info)) {
            Log::channel('xytscmdlog')->debug('资源商不存在或已被删除');
            die;
        }

        try {
            //先同步类型
            $obj = new XytsController();
            $resourceModel = new ResourceXyts();
            $resourceTypeExternalModel = new ResourceTypeExternal();
            $data_type = $obj->getType();
            if ($data_type) {
                $result_id = '';
                foreach ($data_type['data'] as $key => $val) {
                    $val['name'] = $val['classify_name'];
                    $val['class_type_id'] = $val['classify_id'];
                    $val['resource_business_id'] = $this->resource_business_id;
                    $val['big_type_id'] = 2;
                    $result = $resourceTypeExternalModel->getTypeNameNoAdd($val);

                    $result_id .= $result . '、';
                }
                trim($result_id, '、');
                Log::channel('xytscmdlog')->debug('新语听书数据类型同步完成: ' . $result_id);
            }

            //重新获取所有分类
            $self_type_all = $resourceTypeExternalModel->select('id', 'big_type_id', 'class_type_id', 'type_name')->where('resource_business_id', $this->resource_business_id)->where('is_del', 1)->get()->toArray();

            foreach ($self_type_all as $self_type) {
                //获取数据上架列表
                $up_data = $obj->getTypeBookList($self_type['class_type_id'], 1, 1); //获取总数据量
                if ($up_data) {
                    $limit = $this->limit;
                    $total = $up_data['total_page'];
                    $total_page = (int)ceil($total / $limit) + 1; //多增加一页，才能走else

                    //获取所有数据和现在更新的数据做对比，如果没有则删除，有则不做处理 ,按类型删除
                    $data_unique_id_all = $resourceModel->select('guid', 'data_unique_id')->where('type_id', $self_type['id'])->where('resource_business_id', $this->resource_business_id)->where('is_del', 1)->get()->toArray();
                    $data_unique_id_all = array_column($data_unique_id_all, 'guid', 'data_unique_id');

                    for ($i = 1; $i <= $total_page; $i++) {
                        $data = $obj->getTypeBookList($self_type['class_type_id'], $i, $limit); //获取总数据量
                        if ($data) {
                            $result_id = '';
                            foreach ($data['data'] as $key => $val) {
                                $val['type_id'] = $self_type['id'];

                                //删除指定的值
                                unset($data_unique_id_all[$val['book_id']]);

                                $result = $resourceModel->addData($val);
                                $result_id .= $result . '、';
                            }
                            Log::channel('xytscmdlog')->debug('全量同步上架数据, 类型ID: ' . $self_type['class_type_id'] . '; 类型名称：' . $self_type['type_name'] . '; 第 ' . $i . ' 页数据处理完毕: ' . $result_id);
                        } else {
                            //删除本地更新不存在的数据
                            if (!empty($data_unique_id_all)) {
                                $result_id = '';
                                foreach ($data_unique_id_all as $key => $val) {
                                    $del_id = $resourceModel->deleteData($key);
                                    $result_id .= $del_id . '、';
                                }
                                Log::channel('xytscmdlog')->debug('删除本地更新不存在的数据，处理完毕, 类型ID: ' . $self_type['class_type_id'] . '; 类型名称：' . $self_type['type_name'] . ';数据ID: ' . $result_id);
                            }
                            Log::channel('xytscmdlog')->debug('全量同步上架数据处理完毕, 类型ID: ' . $self_type['class_type_id'] . '; 类型名称：' . $self_type['type_name'] . '; 页数: ' . $i);

                            break;
                        }
                    }
                }
            }
            Log::channel('xytscmdlog')->debug('数据全部同步完成');
            // echo '数据全部同步完成';
            //更新同步时间
            $resourceBusinessNameModel->where('id', $this->resource_business_id)->update(['last_synch_time' => date('Y-m-d H:i:s')]);
        } catch (\Exception $e) {
            Log::channel('xytscmdlog')->debug('数据处理出现异常:' . $e->getMessage() . ';File:' . $e->getFile() . ';Line:' . $e->getLine() . ';');
        }
    }
}
